import sys; sys.path.insert(0,'third_party'); sys.path.insert(0,'.')
from twisted.enterprise import adbapi 
from twisted.python.util import println
from twisted.internet import reactor, defer
import traceback
import sqlite3

def printError(failure):
    print "Failure in deferred".center(30, '#')
    print str(failure)
    print "End of failure".center(30, '#')

_addCallback = defer.Deferred.addCallback
def addCallback(d, *args, **kwargs):
    _addCallback(d, *args, **kwargs)
    d.addErrback(printError)
defer.Deferred.addCallback = addCallback
def _createTable(txn, table):
    print "create table"
    try:
        txn.execute("create table if not exists %s (a int, b text)" % table)    
    except:
        print traceback.print_exc()

def createTable(table):
    return dbpool.runInteraction(createTable, table)

def _insertValues(txn, table):
    print "insert values"
    try:
        txn.execute('insert into %s values (1123,"aasdf")' % table )
        txn.execute('insert into %s values (212321,"bsdfsdf")' % table)
        txn.execute('insert into %s values (3123,"cdsffds")' % table)
    except:
        traceback.print_exc()
def insertValues(ignore, table):    
    return dbpool.runInteraction(_insertValues, table)
def _selectAll(txn, table):
    print "select all"
    res = txn.execute('select * from %s' % table)
    return [[x for x in row] for row in res]         
def selectAll(ignored, table):
    return dbpool.runQuery('select * from %s' % table)
def printRes(res):
    print "print results"
    for row in res:
        print row
    
def doIt():
    global dbpool
    dbpool = adbapi.ConnectionPool("sqlite3", '/tmp/test',check_same_thread=False)
    table = 'test'
    #d = createTable(table)
    #d2 = insertValues
    #d.addCallback(insertValues, table)        
    d = selectAll(None, table)
    d.addCallback(printRes)
    con = sqlite3.connect('/tmp/test')
    res = con.execute('select * from test')
    for row in res:
        print row
        
reactor.callLater(1, doIt)
reactor.callLater(4, reactor.stop)    
reactor.run()

